package src.leetcode.everyday.hard_0329;

/**
 * @author liyizzz
 * @description 矩阵中的最长递增路径
 * @date 2025/1/15 14:57
 */
public class longestIncreasingPath {
    public static void main(String[] args) {
        int[][] matrix = new int[][]{{7,8,9},{9,7,6},{7,2,3}};
        System.out.println(new Solution().longestIncreasingPath(matrix));
    }
}


class Solution {
    public int longestIncreasingPath(int[][] matrix) {
        int n = matrix.length, m = matrix[0].length;
        int[][][] dp = new int[n][m][2];
        int max = 1;
        dp[0][0][0] = 1;
        dp[0][0][1] = 1;
        for(int i = 1; i < n; i++) {
            dp[i][0][1] = 1;
            dp[i][0][0] = 1;
            if (matrix[i][0] > matrix[i - 1][0]) {
                dp[i][0][0] = dp[i - 1][0][0] + 1;
            } else if (matrix[i][0] < matrix[i - 1][0]) {
                dp[i][0][1] = dp[i - 1][0][1] + 1;
            }
            max = Math.max(max, Math.max(dp[i][0][0], dp[i][0][1]));
        }

        for(int j = 1; j < m; j++) {
            dp[0][j][1] = 1;
            dp[0][j][0] = 1;
            if (matrix[0][j] > matrix[0][j - 1]) {
                dp[0][j][0] = dp[0][j - 1][0] + 1;
            } else if (matrix[0][j] < matrix[0][j - 1]) {
                dp[0][j][1] = dp[0][j - 1][1] + 1;
            }
            max = Math.max(max, Math.max(dp[0][j][0], dp[0][j][1]));
        }


        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                int c1 = 1, c2 = 1;
                int r1 = 1, r2 = 1;
                if (matrix[i][j] > matrix[i - 1][j]) {
                    c1 = dp[i - 1][j][0] + 1;
                } else if (matrix[i][j] < matrix[i - 1][j]) {
                    r1 = dp[i - 1][j][1] + 1;
                }

                if (matrix[i][j] > matrix[i][j - 1]) {
                    c2 = dp[i][j - 1][0] + 1;
                } else if (matrix[i][j] < matrix[i][j - 1]) {
                    r2 = dp[i][j - 1][1] + 1;
                }

                dp[i][j][0] = Math.max(c1, c2);
                dp[i][j][1] = Math.max(r1, r2);
                max = Math.max(max, Math.max(c1 + r2 - 1, r1 + c2 - 1));
            }
        }
        return max;
    }
}